package rpc

import (
	"context"

	"google.golang.org/grpc"

	"bilinadmin/internal/service"

	pb "bilinadmin/api/pb/server"
)

type permHandler struct {
	*RpcBase
	pb.UnimplementedBilinPermissionServer
	name string
}

// NewPermissionRpcHandler 初始化 permission rpc handler
func NewPermissionRpcHandler() *permHandler {
	return &permHandler{
		RpcBase:                            base,
		UnimplementedBilinPermissionServer: pb.UnimplementedBilinPermissionServer{},
		name:                               "rpc_bilin_admin_handler",
	}
}

// Register 注册服务 handler
func (p *permHandler) Register(server *grpc.Server) {
	pb.RegisterBilinPermissionServer(server, p)
}

// PermissionCheck 品牌门店权限校验
func (p *permHandler) PermissionCheck(ctx context.Context, req *pb.PermissionCheckReq) (*pb.PermissionCheckReply, error) {
	if req == nil {
		return &pb.PermissionCheckReply{}, nil
	}
	has, errL := service.GetRolePermissionSrv().PermissionVerify(ctx, req.BrandId, req.StoreId, req.EmpId, req.Router)
	if errL != nil {
		return nil, errL
	}
	return &pb.PermissionCheckReply{HasPermission: has}, nil
}

// InventoryPermissionCheck 仓库权限校验
func (p *permHandler) InventoryPermissionCheck(ctx context.Context, req *pb.InventoryPermissionCheckReq) (*pb.PermissionCheckReply, error) {
	if req == nil {
		return &pb.PermissionCheckReply{}, nil
	}
	has, errL := service.GetRolePermissionSrv().InventoryPermissionVerify(ctx, req.InvId, req.EmpId)
	if errL != nil {
		return nil, errL
	}
	return &pb.PermissionCheckReply{HasPermission: has}, nil
}

func (p *permHandler) PermissionCheckByToken(ctx context.Context, req *pb.TokenPermissionCheckReq) (*pb.TokenPermissionCheckReply, error) {
	if req == nil {
		return &pb.TokenPermissionCheckReply{}, nil
	}
	token, errL := service.GetService().VerifyBilinToken(req.Token)
	if errL != nil {
		return nil, errL
	}
	has, errL := service.GetRolePermissionSrv().PermissionVerify(ctx, token.BrandId, req.StoreId, token.EmpId, req.Router)
	if errL != nil {
		return nil, errL
	}
	return &pb.TokenPermissionCheckReply{
		HasPermission: has,
		BrandId:       token.BrandId,
		StoreId:       req.StoreId,
		EmpId:         token.EmpId,
		EmpName:       token.Name,
		Router:        req.Router,
	}, nil

}
